package com.sorhis.common.aspect;

import com.sorhis.common.enums.AuthMsgEnum;
import com.sorhis.common.exception.SysException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 切面组件
 */
@Component
@Aspect
@Slf4j
public class AuthorityAspect {

    //定义aop规则
    @Pointcut("within(com.sorhis.controller..*) && " +
            "!within(com.sorhis.controller.LoginController)"
            ) //排除指定方法
    public void pointCutWithin() {


    }

    //使用
    @Before("pointCutWithin()")
    public void AuthManager(JoinPoint point) throws Throwable {
        System.out.println("进入权限AOP--------------------");
        //step1
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); // 获取request
        this.verifyLogin(request); //验证token
        //step2
        this.authentication(point);
    }

    /**
     * 验证token
     * @param request
     */
    private void verifyLogin(HttpServletRequest request) {
//        if (StringUtils.isBlank(request.getHeader("token"))) {
//            throw new SysException(AuthMsgEnum.TOKEN_EXIST_ERROR.getCode(), AuthMsgEnum.TOKEN_EXIST_ERROR.getMessage());
//        }
//        RunData runData = new RunData(); //运行时数据
//        String token = AESUtil.AESDecode(request.getHeader("token")); // 解密token
//        String[] split = token.split("-");
//        runData.getSysUserDTO().setId(split[0]);
//        runData.getSysUserDTO().setName(split[1]);
//        runData.getSysUserDTO().setUserCode(split[5]);
//        Subject.setLocalRunData(runData);
        //查看redis 是否存在
//        if(!RedisUtil.hasKey("login_user_info", split[0])){
//            throw new SysException(AuthMsgEnum.REDIS_NOT_EXIST_ERROR.getCode(), AuthMsgEnum.REDIS_NOT_EXIST_ERROR.getMessage());
//        }
//
//        //验证token是否过期
//        if (this.compare(split[4])) {
//            throw new SysException(AuthMsgEnum.EXP_TIME_ERROR.getCode(), AuthMsgEnum.EXP_TIME_ERROR.getMessage());
//        }
    }

    /**
     * 验证权限
     * @param point
     */
    private void authentication(JoinPoint point){
        // 管理员直接跳过
//        if(Subject.getLocalRunData().getSysUserDTO().getName().equals("管理员")){
//            return ;
//        }
//        //用户权限标识
//        List<String> userCodeList = iSysMenusService.findAuthCodeByUserId(Subject.getLocalRunData().getSysUserDTO());
//        log.info("用户所有权限>>>>>>>>>>>>>>>>>>>>>>>{}", userCodeList);
//        Method method = ((MethodSignature) point.getSignature()).getMethod();
//        String methodName = point.getSignature().getName();
//        System.out.println("-----进入aop了------方法名称：》》》》" + methodName);
//        PermissionsAnnotations annotation = method.getAnnotation(PermissionsAnnotations.class);
//        if(annotation != null){
//            System.out.println("注解内容：》》》》" + annotation.value().getValue());
//            String code = annotation.value().getValue();
//            if(userCodeList.indexOf(code) < 0){ //如果用户的权限标识不存在
//                throw new SysHrException(AuthMsgEnum.AUTH_ERROR.getCode(), AuthMsgEnum.AUTH_ERROR.getMessage());
//            }
//        }
    }

    public boolean compare(String exp_time) {
        DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        try {
            Date beginDate = df.parse(df.format(new Date())); //当前时间
            log.info("token当前时间-----{}" , beginDate);
            Date endDate = df.parse(exp_time);
            log.info("token过期时间-----{}" , endDate);
            log.info("token过期时间比较-----{}" , endDate.getTime() > beginDate.getTime());
            if (endDate.getTime() > beginDate.getTime()) {
                return false; // 未超时
            } else if (endDate.getTime() < beginDate.getTime()) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true; // 默认是超时
    }

}
